// pages/category/category.js
import { dishApi, setmealApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { CATEGORY_TYPE } from '../../utils/constants.js'

const app = getApp()

Page({
  data: {
    loading: true,
    categoryId: null,
    categoryName: '',
    categoryType: CATEGORY_TYPE.DISH,
    dishes: [],
    setmeals: [],
    activeTab: 'dish', // dish 或 setmeal
    cartCount: 0
  },

  onLoad(options) {
    const { id, name, type } = options
    this.setData({
      categoryId: id,
      categoryName: decodeURIComponent(name || ''),
      categoryType: type ? parseInt(type) : CATEGORY_TYPE.DISH
    })
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: this.data.categoryName
    })
    
    this.loadData()
  },

  onShow() {
    // 更新购物车数量
    this.updateCartCount()
  },

  onPullDownRefresh() {
    this.loadData()
  },

  onReachBottom() {
    // 可以在这里实现加载更多功能
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ loading: true })
      
      if (this.data.categoryType === CATEGORY_TYPE.DISH) {
        await this.loadDishes()
      } else {
        await this.loadSetmeals()
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 加载菜品数据
  async loadDishes() {
    try {
      const res = await dishApi.getListByCategory({
        categoryId: this.data.categoryId
      })
      
      if (res.code === 1) {
        this.setData({
          dishes: res.data,
          activeTab: 'dish'
        })
      }
    } catch (error) {
      console.error('加载菜品失败:', error)
    }
  },

  // 加载套餐数据
  async loadSetmeals() {
    try {
      const res = await setmealApi.getListByCategory({
        categoryId: this.data.categoryId
      })
      
      if (res.code === 1) {
        this.setData({
          setmeals: res.data,
          activeTab: 'setmeal'
        })
      }
    } catch (error) {
      console.error('加载套餐失败:', error)
    }
  },

  // 更新购物车数量
  updateCartCount() {
    app.updateCartCount()
    this.setData({
      cartCount: app.globalData.cartCount
    })
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
    
    if (tab === 'dish' && this.data.dishes.length === 0) {
      this.loadDishes()
    } else if (tab === 'setmeal' && this.data.setmeals.length === 0) {
      this.loadSetmeals()
    }
  },

  // 跳转到菜品详情
  goToDishDetail(e) {
    const dishId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/dish/dish?id=${dishId}`
    })
  },

  // 跳转到套餐详情
  goToSetmealDetail(e) {
    const setmealId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/setmeal/setmeal?id=${setmealId}`
    })
  },

  // 添加到购物车
  async addToCart(e) {
    if (!checkLoginAndRedirect()) return
    
    const { id, type } = e.currentTarget.dataset
    const { dishFlavor } = e.currentTarget.dataset
    
    try {
      wx.showLoading({ title: '添加中...' })
      
      const data = {
        dishFlavor: dishFlavor || ''
      }
      
      if (type === 'dish') {
        data.dishId = id
      } else {
        data.setmealId = id
      }
      
      const res = await wx.request({
        url: `${app.globalData.baseUrl}/user/shoppingCart/add`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data
      })
      
      if (res.data.code === 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        this.updateCartCount()
      } else {
        throw new Error(res.data.msg || '添加失败')
      }
    } catch (error) {
      console.error('添加到购物车失败:', error)
      wx.showToast({
        title: error.message || '添加失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 跳转到购物车
  goToCart() {
    if (!checkLoginAndRedirect()) return
    
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: `${this.data.categoryName} - 美味外卖`,
      path: `/pages/category/category?id=${this.data.categoryId}&name=${encodeURIComponent(this.data.categoryName)}`,
      imageUrl: '/images/share.jpg'
    }
  }
})
